package com.micrometa.km.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
	public static void copy(File src, File dst) throws IOException {
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);
		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;
		try {
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		} finally {
			in.close();
			out.close();
		}
	}

	public static void copyAll(File src, File dest) throws IOException {
		if (src.isDirectory()) {
			if (!dest.exists()) {
				boolean ret = dest.mkdir();
				if (ret == false)
					return;
			}
			File[] fs = src.listFiles();
			for (int i = 0; i < fs.length; i++) {
				copyAll(fs[i], new File(dest, fs[i].getName()));
			}
			return;
		}
		byte[] buf = new byte[1024];
		FileInputStream in = new FileInputStream(src);
		FileOutputStream out = new FileOutputStream(dest);
		int len;
		try {
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		} finally {
			in.close();
			out.close();
		}
	}

	private final static String filter = ".svn";

	/**
	 * if no filter string return true.
	 * 
	 * @param f
	 * @return
	 */
	public static boolean filter(File f) {
		if (f != null && f.canRead())
			if (!f.getName().equals(filter))
				return true;
			else
				return false;
		else
			return false;
	}

	public static boolean delete(File f) {
		boolean re = true;
		if (f != null && f.canRead() && f.canExecute()) {
			if (f.isFile()) {
				f.delete();
			} else if (f.isDirectory()) {
				File[] fs = f.listFiles();
				for (File ff : fs)
					delete(ff);
				f.delete();
			}
		} else
			re = false;
		return re;
	}

	public static void main(String[] args) throws Exception {
		// System.out.println(Thread.currentThread().getContextClassLoader()
		// .getResource(""));
		// System.out.println(FileUtil.class.getClassLoader().getResource(""));
		// System.out.println(ClassLoader.getSystemResource(""));
		// System.out.println(FileUtil.class.getResource(""));
		// System.out.println(FileUtil.class.getResource("/"));
		// System.out.println(new File("").getAbsolutePath());
		// System.out.println(System.getProperty("user.dir"));
		// System.out.println(new File("E:\\workspace\\wmkm\\repository\\test")
		// .delete());
	}
}
